package com.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dao.userDao;
import com.dao.usersDao;
import com.dao.uservehicleDao;
import com.pojo.User;
import com.pojo.Users;
import com.pojo.Uservehicle;
import com.pojo.vo.vo_ResponseBody;
import com.pojo.vo.vo_User;
import com.service.LoginService;
import com.utils.JedisClient;
import com.utils.StringUtil;
import com.utils.UserAuth;
import com.utils.jedis.JedisClientUser;

import redis.clients.jedis.exceptions.JedisConnectionException;
import rest.RestTest;

@Service("loginService")
public class LoginServiceImpl implements LoginService {

	@Autowired
	private userDao userDao;

	@Autowired
	private usersDao usersDao;

	@Autowired
	private uservehicleDao uservehicleDao;

	private JedisClient jedisClient;

	public String login(UserAuth userAuth) {
		jedisClient = new JedisClientUser();// redis 键：cardid的hashcode值
											// 值：vo_user:用户名，用户服务
		if (!userAuth.isFirstLogin()) {
			if (userAuth.getUser_cardId_hash() != null && userAuth.getUser_cardId_hash().length() > 0) {// 用户已登录过则有这个hash值
				String token = jedisClient.hget(userAuth.getUser_cardId_hash(), "token");// 通过hash值得到已有token
				if (token == null) {
					return JSONArray.toJSONString(new vo_ResponseBody(0, -1, "登录过期"));
				} else if (userAuth.getToken().equals(token)) {// 和已经获得的token比较,如果不想同，则说明在别的地方登录过
					return JSONArray.toJSONString(new vo_ResponseBody(0, 0, JSONArray.toJSONString(userAuth)));
				} else {
					return JSONArray.toJSONString(new vo_ResponseBody(0, -1, "您需要重新登录"));
				}
			} else {
				return JSONArray.toJSONString(new vo_ResponseBody(0, -1, "登录错误，请重新登录"));
			}
		} else {
			User user = userDao.login(userAuth.getUserName(), userAuth.getUserPass());
			if (user == null) {
				return JSONArray.toJSONString(new vo_ResponseBody(0, -1, "账号不存在"));
			}
			if (!user.getUser_pass().equals(userAuth.getUserPass())) {
				return JSONArray.toJSONString(new vo_ResponseBody(0, -1, "密码错误"));
			}
			Users users = usersDao.login(user.getUser_id(), userAuth.getUserType_id());// 必定存在一个或多个服务
			if (users == null) {
				return JSONArray.toJSONString(new vo_ResponseBody(0, -1, "您还没有注册该服务"));
			}
			if(!users.isUsers_enable()){
				return JSONArray.toJSONString(new vo_ResponseBody(0, -1, "请您通过审核后再登录"));
			}
			int user_card_hash = user.getUser_cardId().hashCode();
			String user_cardId_hash = String.valueOf(user_card_hash);
			String user_name = user.getUser_name();
			vo_User vo_user = new vo_User(user_name, user.getUser_tel(), users.getUser_type_id());
			userAuth.setUser_cardId_hash(user_cardId_hash);
			userAuth.setUsers_id(users.getUsers_id());
			userAuth.setToken(UUID.randomUUID().toString());// token 为UUID生成
			userAuth.setFirstLogin(false);
			jedisClient.hset(user_cardId_hash, "token", userAuth.getToken());
			jedisClient.hset(user_cardId_hash, "data", JSONArray.toJSONString(vo_user));
			return JSONArray.toJSONString(new vo_ResponseBody(0, 0, JSONArray.toJSONString(userAuth)));
		}
	}

	@Override
	public String getUserAndType(String user_CardId_hash) {
		String data = "获取个人信息";
		jedisClient = new JedisClientUser();// redis 键：cardid的hashcode值
											// 值：vo_user:用户名，用户服务
		vo_User vo_user = JSONArray.parseObject(jedisClient.hget(user_CardId_hash, "data"), vo_User.class);
		User user = userDao.getUserByUser_tel(vo_user.getUser_tel());
		JSONObject json = new JSONObject();
		json.putIfAbsent("user", user);
		if (vo_user.getUser_type_id() == 3) {
			Users users = usersDao.getUsersByUser_idAndType_id(user.getUser_id(), 3);
			Uservehicle uservehicle = uservehicleDao.getOneByUser_id(users.getUsers_id());
			json.putIfAbsent("uservehicle", uservehicle == null ? "" : uservehicle);
			return JSONArray.toJSONString(new vo_ResponseBody(0, 0, JSONArray.toJSONString(json)));
		}
		return JSONArray.toJSONString(new vo_ResponseBody(0, 0, JSONArray.toJSONString(json)));
	}

	@Override
	public String edit(User editUser, Integer user_type_id, Uservehicle editUservehicle) {
		int i = userDao.editUserByUser(editUser);// 修改个人信息
		int j = 0;
		if (user_type_id == 3) { // 如果用户是车主，还需要修改车主端信息
			j = uservehicleDao.editUservehicleByUservehicle(editUservehicle);
		}
		if (i > 0 || j > 0) {
			return JSONArray.toJSONString(new vo_ResponseBody(0, 0, "修改成功"));
		} else {
			return JSONArray.toJSONString(new vo_ResponseBody(0, 0, "暂未修改任何信息"));
		}
	}

	@Override
	public String reg_getCheckcode(String phoneImei, String mobile) {
		if (!StringUtil.isMobile(mobile)) {
			return JSONArray.toJSONString(new vo_ResponseBody(0, -1, "请正确输入手机号"));
		}
		try {
			String code = StringUtil.getCodeByCount(6);// 生成验证码
			System.out.println("验证码： "+code);
			jedisClient = new JedisClientUser();
			jedisClient.set(phoneImei + mobile, code);// redis中记录本次验证码
			jedisClient.expire(phoneImei + mobile, 180);
			String result = RestTest.registerSendSms(code, mobile);// 返回发送结果
			JSONObject json = JSONArray.parseObject(result);
			if (json.getString("count").equals(0) || !json.getString("msg").equals("OK")) {// 代表短信发送失败
				jedisClient.del(phoneImei + mobile);// redis中删除本次验证码
			}
		} catch (JedisConnectionException e1) {
			return JSONArray.toJSONString(new vo_ResponseBody(0, -1, "验证码发送失败"));
		} catch (Exception e) {
			return JSONArray.toJSONString(new vo_ResponseBody(0, -1, "验证码发送失败"));
		}
		return JSONArray.toJSONString(new vo_ResponseBody(0, 0, "请及时查收验证码"));
	}

}
